<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Operate extends MY_Controller
{

    /**
     * @var ConsumerOrderModel
     */
    public $mOrder = null;

    public function __construct()
    {
        parent::__construct();
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
    }

    /**
     * 首页
     */
    public function index()
    {
        $timeGap = trim(post('timegap'));
        if (!$timeGap) {
            // 最近3天
            $startTime = strtotime("-3 day");
            $endTime = 0;
        } else {
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]) + 86399;
            $dayA = ceil(($endTime - $startTime) / 86400);
            if ($dayA > 100) {
                $endTime = strtotime("+3 month", $startTime);
            }
        }
        $countAll = $this->mOrder->getOperateStatisticsCount($startTime, $endTime);
        $list = $this->mOrder->getOperateStatisticsList($startTime, $endTime);


        $result = array(
            'order' => array(),
            'total_amount' => array(),
            'discount_amount' => array(),
            'reality_amount' => array(),
            'time' => array()
        );
        foreach ($list as $k => $v) {
            $result['order'][] = $v['total'];
            $result['total_amount'][] = $v['total_amount'];
            $result['discount_amount'][] = $v['discount_amount'];
            $result['reality_amount'][] = $v['reality_amount'];
            $result['time'][] = $v['time'];
        }

        $endTime = $endTime == 0 ? time() : $endTime;
        $data = array(
            'result' => json_encode($result),
            'list' => $list,
            'countAll' => $countAll,
            'timeGap' => $timeGap,
            'startTime' => dateFormat($startTime),
            'endTime' => dateFormat($endTime),
        );
        $this->view('statistics/operate/index', $data, 'datatable,date_range_picker,e_chart');
    }

    /**
     * 按天统计列表
     */
    public function statisticsDateList()
    {
        $startTime = trim(get('startTime'));
        $endTime = trim(get('endTime'));

        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime) + 86399;
        $datelist = $this->mOrder->getOperateStatisticsDateList($startTime, $endTime);
        foreach ($datelist['data'] as $k => $v) {
            $datelist['aaData'][$k][] = $v['time'];
            $datelist['aaData'][$k][] = $v['product_amount'];
            $datelist['aaData'][$k][] = $v['shipping_fee'];
            $datelist['aaData'][$k][] = $v['bonus'];
            $datelist['aaData'][$k][] = $v['postal_card'];
            $datelist['aaData'][$k][] = $v['merchant_discount'];
            $datelist['aaData'][$k][] = $v['reality_amount'];
            $datelist['aaData'][$k][] = $v['total_order'];
            $datelist['aaData'][$k][] = $v['total_user'];
            $datelist['aaData'][$k][] = $v['change_amount'];
            $datelist['aaData'][$k][] = $v['sign'];
            $datelist['aaData'][$k][] = $v['sale_order'];
            $datelist['aaData'][$k][] = $v['sale_amount'];
            $btnConfig = adminCreateBtn(array(
                'label' => '查看',
                'attr' => array(
                    'href' => getUrl('statistics/operate/statisticsDate?time=' . $v['time']),
                    'class' => 'btn green-stripe btn-xs default'
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'order',
                    'key' => 'home-details'
                )
            ));
            $datelist['aaData'][$k][] = $btnConfig;
        }
        unset($datelist['data']);
        echo json_encode($datelist);
    }

    /**
     * 按商家统计列表
     */
    public function getOperateStatisticsMerchantList()
    {
        $startTime = trim(get('startTime'));
        $endTime = trim(get('endTime'));

        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime) + 86399;
        $datelist = $this->mOrder->getOperateStatisticsMerchantList($startTime, $endTime);
        foreach ($datelist['data'] as $k => $v) {
            $datelist['aaData'][$k][] = $v['nickname'];
            $datelist['aaData'][$k][] = $v['product_amount'];
            $datelist['aaData'][$k][] = $v['shipping_fee'];
            $datelist['aaData'][$k][] = $v['bonus'];
            $datelist['aaData'][$k][] = $v['postal_card'];
            $datelist['aaData'][$k][] = $v['merchant_discount'];
            $datelist['aaData'][$k][] = $v['reality_amount'];
            $datelist['aaData'][$k][] = $v['total_order'];
            $datelist['aaData'][$k][] = $v['total_user'];
            $datelist['aaData'][$k][] = $v['change_amount'];
            $datelist['aaData'][$k][] = $v['sign'];
            $datelist['aaData'][$k][] = $v['sale_order'];
            $datelist['aaData'][$k][] = $v['sale_amount'];
            $btnConfig = adminCreateBtn(array(
                'label' => '查看',
                'attr' => array(
                    'href' => getUrl('statistics/operate/statisticsMerchant?id=' . $v['merchant_id'] . '&startTime=' . $startTime . '&endTime=' . $endTime),
                    'class' => 'btn green-stripe btn-xs default'
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'order',
                    'key' => 'home-details'
                )
            ));
            $datelist['aaData'][$k][] = $btnConfig;
        }
        unset($datelist['data']);
        echo json_encode($datelist);
    }

    /**
     * 订单详情
     */
    public function statisticsDate()
    {
        //表单验证
        $vConf = array(
            array('time', '当天时间', 'required'),
        );
        $this->formDataValidation($vConf, array('time' => get('time')));
        $time = trim(get('time'));
        $startTime = strtotime($time);
        $endTime = $startTime + 86400;
        $info = $this->mOrder->getOperateStatisticsCount($startTime, $endTime);
        $data = array(
            'pay_type' => $this->mOrder->PAY_TYPE,
            'expense_type' => $this->mOrder->EXPENSE_TYPE,
            'status'=> $this->mOrder->status(),
            'serviceType' => $this->mOrder->serviceType(),
            'info' => $info,
            'time' => $time,
            'title' => '统计详情'
        );
        $this->view('statistics/operate/orderList', $data, 'datatable,datepicker');
    }

    public function statisticsMerchant()
    {
        //表单验证

        $id = trim(get('id'));
        $startTime = trim(get('startTime'));
        $endTime = trim(get('endTime'));
        $info = $this->mOrder->getOperateStatisticsCount($startTime, $endTime, array(), $id);
        $startTime = dateFormat($startTime);
        $endTime = dateFormat($endTime);
        $data = array(
            'info' => $info,
            'pay_type' => $this->mOrder->PAY_TYPE,
            'expense_type' => $this->mOrder->EXPENSE_TYPE,
            'status'=> $this->mOrder->status(),
            'serviceType' => $this->mOrder->serviceType(),
            'startTime' => $startTime,
            'endTime' => $endTime,
            'id' => $id,
            'title' => '统计详情'
        );
        $this->view('statistics/operate/orderList2', $data, 'datatable,datepicker');
    }

    /**
     * 获取订单详情列表
     */
    public function getOrderList()
    {
        $id = (int)get('id');
        if (!$id) $id = 0;

        $data = $this->mOrder->adminPcGetOrderList($id);
        foreach ($data['data'] as $k => $v) {
            $data['aaData'][$k][] = $v['code'];
            $data['aaData'][$k][] = $v['merchant'] . '<br>' . $v['store_tel'];
            $data['aaData'][$k][] = $v['consumerName'] . '<br>' . $v['consumer'];
            $data['aaData'][$k][] = $this->mOrder->expenseType($v['expense_type']);
            $data['aaData'][$k][] = $this->mOrder->payType($v['pay_type']);
            $data['aaData'][$k][] = dateFormat($v['addtime']);
            $data['aaData'][$k][] = dateFormat($v['merchant_take_time']);
            $data['aaData'][$k][] = $v['total_amount'];
            $data['aaData'][$k][] = $v['discount'];
            $data['aaData'][$k][] = $v['change_amount'];
            $data['aaData'][$k][] = $v['reality_amount'];
            if ($v['expense_type'] == 2) {
                $data['aaData'][$k][] = $this->mOrder->storeStatus($v['status'], true);
            } else {
                $data['aaData'][$k][] = $this->mOrder->status($v['status'], true);
            }
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => '查看',
                'attr' => array(
                    'href' => getUrl('order/home/details?id=' . $v['id']),
                    'class' => 'btn green-stripe btn-xs default',
                    'target' => '_blank'
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'classes',
                    'key' => 'edit'
                )
            ));
        }
        unset($data['data']);
        echo json_encode($data);
    }

    public function getAfterOrderList()
    {
        $id = (int)get('id');
        if (!$id) $id = 0;

        $data = $this->mOrder->adminPcGetOrderServiceList($id);
        foreach ($data['data'] as $k => $v) {
            $data['aaData'][$k][] = $v['code'];
            $data['aaData'][$k][] = $v['order_code'];
            $data['aaData'][$k][] = $v['shop_name'];
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['remark'];
            $data['aaData'][$k][] = $v['refund_amount'];
            $data['aaData'][$k][] = dateFormat($v['complete_time']);
            $data['aaData'][$k][] = $this->mOrder->serviceType($v['status'], true);
            $data['aaData'][$k][] = adminCreateBtn(array(
                'label' => '查看',
                'attr' => array(
                    'href' => getUrl('order/service/details?code=' . $v['code']),
                    'class' => 'btn green-stripe btn-xs default',
                    'target' => '_blank'
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'classes',
                    'key' => 'edit'
                )
            ));
        }
        unset($data['data']);
        echo json_encode($data);

    }

    /**
     * 导出
     */
    public function export()
    {
        $this->load->library('PHPExcel/PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        date_default_timezone_set('Asia/Shanghai');
        $objPHPExcel = new PHPExcel();

        $objPHPExcel->getProperties()->setTitle("销售运营表")
            ->setSubject("销售运营表")
            ->setDescription("销售运营表")
            ->setKeywords("excel")
            ->setCategory("result file");

        $timeGap = trim(get('time'));
        if (!$timeGap){
            // 最近10天
            $startTime = strtotime("-10 day");
            $endTime = 0;
        }else{
            $timeGapArr = explode(' - ', $timeGap);
            $startTime = strtotime($timeGapArr[0]);
            $endTime = strtotime($timeGapArr[1]) + 86399;
            $dayA = ceil(($endTime-$startTime)/86400);
            if ($dayA > 100){
                $endTime = strtotime("+3 month",$startTime);
            }
        }
        //按日期查询
        $objPHPExcel->getActiveSheet()->setTitle('按日期统计');
        //构建表头
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->mergeCells('A1:A2')->setCellValue("A1","日期");
        $objPHPExcel->getActiveSheet()->mergeCells('B1:C1')->setCellValue("B1","订单总额");
        $objPHPExcel->getActiveSheet()->setCellValue("B2","商品总额");
        $objPHPExcel->getActiveSheet()->setCellValue("C2","配送费");
        $objPHPExcel->getActiveSheet()->mergeCells('D1:F1')->setCellValue("D1","优惠金额");
        $objPHPExcel->getActiveSheet()->setCellValue("D2","平台红包");
        $objPHPExcel->getActiveSheet()->setCellValue("E2","包邮卡");
        $objPHPExcel->getActiveSheet()->setCellValue("F2","商家优惠");
        $objPHPExcel->getActiveSheet()->mergeCells('G1:G2')->setCellValue("G1","实付金额");
        $objPHPExcel->getActiveSheet()->mergeCells('H1:H2')->setCellValue("H1","订单数量");
        $objPHPExcel->getActiveSheet()->mergeCells('I1:I2')->setCellValue("I1","下单用户数");
        $objPHPExcel->getActiveSheet()->mergeCells('J1:J2')->setCellValue("J1","退差价");
        $objPHPExcel->getActiveSheet()->mergeCells('K1:K2')->setCellValue("K1","客户单价");
        $objPHPExcel->getActiveSheet()->mergeCells('L1:L2')->setCellValue("L1","售后订单数");
        $objPHPExcel->getActiveSheet()->mergeCells('M1:M2')->setCellValue("M1","售后总额");

        $datelist = $this->mOrder->getOperateStatisticsDateList($startTime, $endTime,array(),true);
        $index = 3;
        foreach ($datelist as $k => $v) {
            $objPHPExcel->getActiveSheet()
                ->setCellValue('A'.$index, $v['time'])
                ->setCellValue('B'.$index, $v['product_amount'])
                ->setCellValue('C'.$index, $v['shipping_fee'])
                ->setCellValue('D'.$index, $v['bonus'])
                ->setCellValue('E'.$index, $v['postal_card'])
                ->setCellValue('F'.$index, $v['merchant_discount'])
                ->setCellValue('G'.$index, $v['reality_amount'])
                ->setCellValue('H'.$index, $v['total_order'])
                ->setCellValue('I'.$index, $v['total_user'])
                ->setCellValue('J'.$index, $v['change_amount'])
                ->setCellValue('K'.$index, $v['sign'])
                ->setCellValue('L'.$index, $v['sale_order'])
                ->setCellValue('M'.$index, $v['sale_amount']);
            $index++;
        }

        $objPHPExcel->createSheet(1);
        $objPHPExcel->setActiveSheetIndex(1);
        $objPHPExcel->getActiveSheet()->setTitle('按商家统计');
        //构建表头
        $objPHPExcel->getActiveSheet()->mergeCells('A1:A2')->setCellValue("A1","商家");
        $objPHPExcel->getActiveSheet()->mergeCells('B1:C1')->setCellValue("B1","订单总额");
        $objPHPExcel->getActiveSheet()->setCellValue("B2","商品总额");
        $objPHPExcel->getActiveSheet()->setCellValue("C2","配送费");
        $objPHPExcel->getActiveSheet()->mergeCells('D1:F1')->setCellValue("D1","优惠金额");
        $objPHPExcel->getActiveSheet()->setCellValue("D2","平台红包");
        $objPHPExcel->getActiveSheet()->setCellValue("E2","包邮卡");
        $objPHPExcel->getActiveSheet()->setCellValue("F2","商家优惠");
        $objPHPExcel->getActiveSheet()->mergeCells('G1:G2')->setCellValue("G1","实付金额");
        $objPHPExcel->getActiveSheet()->mergeCells('H1:H2')->setCellValue("H1","订单数量");
        $objPHPExcel->getActiveSheet()->mergeCells('I1:I2')->setCellValue("I1","下单用户数");
        $objPHPExcel->getActiveSheet()->mergeCells('J1:J2')->setCellValue("J1","退差价");
        $objPHPExcel->getActiveSheet()->mergeCells('K1:K2')->setCellValue("K1","客户单价");
        $objPHPExcel->getActiveSheet()->mergeCells('L1:L2')->setCellValue("L1","售后订单数");
        $objPHPExcel->getActiveSheet()->mergeCells('M1:M2')->setCellValue("M1","售后总额");

        $datelist = $this->mOrder->getOperateStatisticsMerchantList($startTime, $endTime,array(),true);
        $index = 3;
        foreach ($datelist as $k => $v) {
            $objPHPExcel->getActiveSheet()
                ->setCellValue('A'.$index, $v['nickname'])
                ->setCellValue('B'.$index, $v['product_amount'])
                ->setCellValue('C'.$index, $v['shipping_fee'])
                ->setCellValue('D'.$index, $v['bonus'])
                ->setCellValue('E'.$index, $v['postal_card'])
                ->setCellValue('F'.$index, $v['merchant_discount'])
                ->setCellValue('G'.$index, $v['reality_amount'])
                ->setCellValue('H'.$index, $v['total_order'])
                ->setCellValue('I'.$index, $v['total_user'])
                ->setCellValue('J'.$index, $v['change_amount'])
                ->setCellValue('K'.$index, $v['sign'])
                ->setCellValue('L'.$index, $v['sale_order'])
                ->setCellValue('M'.$index, $v['sale_amount']);
            $index++;
        }

        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.date('Y-m-d',$startTime).'至'.date('Y-m-d',$endTime).'销售运营表.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

    }

    /**
     * 导出详情
     */
    public function saleExport()
    {
        $this->load->library('PHPExcel/PHPExcel');
        $this->load->library('PHPExcel/PHPExcel/IOFactory');
        date_default_timezone_set('Asia/Shanghai');
        $objPHPExcel = new PHPExcel();

        //处理请求
        $exportType = trim(get('exportType'));
        $take_time_from = get('take_time_from');
        $take_time_to = get('take_time_to');

        $objPHPExcel->getProperties()->setTitle("销售运营表")
            ->setSubject("销售运营表")
            ->setDescription("销售运营表")
            ->setKeywords("excel")
            ->setCategory("result file");

        $objPHPExcel->getActiveSheet()->setTitle('订单统计');
        //构建表头
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setCellValue("A1","编号");
        $objPHPExcel->getActiveSheet()->setCellValue("B1","商家");
        $objPHPExcel->getActiveSheet()->setCellValue("C1","会员手机");
        $objPHPExcel->getActiveSheet()->setCellValue("D1","消费模式");
        $objPHPExcel->getActiveSheet()->setCellValue("E1","支付方式");
        $objPHPExcel->getActiveSheet()->setCellValue("F1","下单时间");
        $objPHPExcel->getActiveSheet()->setCellValue("G1","接单时间");
        $objPHPExcel->getActiveSheet()->setCellValue("H1","订单总额");
        $objPHPExcel->getActiveSheet()->setCellValue("I1","订单优惠");
        $objPHPExcel->getActiveSheet()->setCellValue("J1","实付金额");
        $objPHPExcel->getActiveSheet()->setCellValue("K1","状态");

        $pageNumber = 500;
        $page = 1;
        $index = 2;
        if($exportType==1){
            $id = 0;
        }else{
            $id = trim(get('id'));
        }
        while (true) {
            $data = $this->mOrder->adminPcGetOrderList($id, 0, array(), array('page' => $page, 'pageNumber' => $pageNumber));
            if (empty($data)) {
                break;
            }
            $page++;
            foreach ($data as $v) {
                $expenseType = $this->mOrder->expenseType($v['expense_type']);
                $payType = $this->mOrder->payType($v['pay_type']);
                $addtime = dateFormat($v['addtime']);
                $merchant_take_time = dateFormat($v['merchant_take_time']);
                if ($v['expense_type'] == 2) {
                    $status = $this->mOrder->storeStatus($v['status']);
                } else {
                    $status = $this->mOrder->status($v['status']);
                }
                $objPHPExcel->getActiveSheet()
                    ->setCellValue('A'.$index, $v['code'])
                    ->setCellValue('B'.$index, $v['merchant'])
                    ->setCellValue('C'.$index, $v['consumer'])
                    ->setCellValue('D'.$index, $expenseType)
                    ->setCellValue('E'.$index, $payType)
                    ->setCellValue('F'.$index, $addtime)
                    ->setCellValue('G'.$index, $merchant_take_time)
                    ->setCellValue('H'.$index, $v['total_amount'])
                    ->setCellValue('I'.$index, $v['discount'])
                    ->setCellValue('J'.$index, $v['reality_amount'])
                    ->setCellValue('K'.$index, $status);
                $index++;
            }
        }

        $objPHPExcel->createSheet(1);
        $objPHPExcel->setActiveSheetIndex(1);
        $objPHPExcel->getActiveSheet()->setTitle('售后订单统计');
        $objPHPExcel->getActiveSheet()->setCellValue("A1","售后单号");
        $objPHPExcel->getActiveSheet()->setCellValue("B1","订单号");
        $objPHPExcel->getActiveSheet()->setCellValue("C1","商家");
        $objPHPExcel->getActiveSheet()->setCellValue("D1","退款商品");
        $objPHPExcel->getActiveSheet()->setCellValue("E1","退款原因");
        $objPHPExcel->getActiveSheet()->setCellValue("F1","退款金额");
        $objPHPExcel->getActiveSheet()->setCellValue("G1","申请时间");
        $objPHPExcel->getActiveSheet()->setCellValue("H1","状态");

        $index = 2;
        $page = 1;
        while (true) {
            $data = $this->mOrder->adminPcGetOrderServiceList($id, 0, array(), array('page' => $page, 'pageNumber' => $pageNumber));
            if (empty($data)) {
                break;
            }
            $page++;
            foreach ($data as $v) {
                $objPHPExcel->getActiveSheet()
                    ->setCellValue('A'.$index, $v['code'])
                    ->setCellValue('B'.$index, $v['order_code'])
                    ->setCellValue('C'.$index, $v['shop_name'])
                    ->setCellValue('D'.$index, $v['name'])
                    ->setCellValue('E'.$index, $v['remark'])
                    ->setCellValue('F'.$index, $v['refund_amount'])
                    ->setCellValue('G'.$index, dateFormat($v['addtime']))
                    ->setCellValue('H'.$index, $this->mOrder->SERVICE_TYPE[$v['status']]);
                $index++;
            }
        }

        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="销售统计-订单详情'.date('Y-m-d', time()).'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }
}
